﻿using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Net.Sockets;
using UnityEditor.UI;
using UnityEngine.UI;

public class NetTalkWindow : MonoBehaviour
{
    const int Port = 8080;//端口号与服务端端口对应
    private TcpClient client;
    byte[] data;
    public string UserName = "";//用户名
    public string message = "";//聊天内容
    public string sendMsg = "";//输入框

    private void OnGUI()
    {
        message = GUI.TextArea(new Rect(750, 885, 320, 125), message);
    }

    public void LinkServer_net()
    {
        this.client = new TcpClient();
        this.client.Connect("49.233.108.158", Port);
        data = new byte[this.client.ReceiveBufferSize];
        SendSocket(UserName);
        this.client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this.client.ReceiveBufferSize), ReceiveMessage, null);
    }

    public void SendMessage_Net()
    {
        SendSocket(sendMsg);
        sendMsg = "";
    }

    public void SendSocket(string message)
    {
        try
        {
            NetworkStream ns = this.client.GetStream();
            byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
            ns.Write(data, 0, data.Length);
            ns.Flush();
        }
        catch (Exception ex)
        {
        }
    }

    public void ReceiveMessage(IAsyncResult ar)
    {
        try
        {
            int bytesRead;
            bytesRead = this.client.GetStream().EndRead(ar);
            if (bytesRead < 1)
            {
                return;
            }
            else
            {
                message += System.Text.Encoding.UTF8.GetString(data, 0, bytesRead);
            }
            this.client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this.client.ReceiveBufferSize), ReceiveMessage, null);
        }
        catch (Exception ex)
        {
        }
    }
    void Start()
    {

    }
    // Update is called once per frame
    void Update()
    {
        UserName = UsernameInputText.uName;//获取用户输入的用户名
        sendMsg = SendMessageText.sMessage;//获取用户输入的待发送信息

    }
}
